import pool from '../config/database';
import { hashPassword, comparePassword } from '../utils/helpers';

// 用户接口
export interface User {
  id: number;
  username: string;
  email: string;
  password: string;
  chips: number;
  created_at: Date;
  updated_at: Date;
}

// 创建用户表
export const createUserTable = async (): Promise<void> => {
  const query = `
    CREATE TABLE IF NOT EXISTS users (
      id SERIAL PRIMARY KEY,
      username VARCHAR(50) UNIQUE NOT NULL,
      email VARCHAR(100) UNIQUE NOT NULL,
      password VARCHAR(255) NOT NULL,
      chips INTEGER DEFAULT 1000,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
  `;
  
  try {
    await pool.query(query);
    console.log('Users table created successfully');
  } catch (error) {
    console.error('Error creating users table:', error);
    throw error;
  }
};

// 根据ID查找用户
export const findUserById = async (id: number): Promise<User | null> => {
  try {
    const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error finding user by ID:', error);
    throw error;
  }
};

// 根据用户名查找用户
export const findUserByUsername = async (username: string): Promise<User | null> => {
  try {
    const result = await pool.query('SELECT * FROM users WHERE username = $1', [username]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error finding user by username:', error);
    throw error;
  }
};

// 根据邮箱查找用户
export const findUserByEmail = async (email: string): Promise<User | null> => {
  try {
    const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error finding user by email:', error);
    throw error;
  }
};

// 创建新用户
export const createUser = async (username: string, email: string, password: string): Promise<User> => {
  try {
    // 哈希密码
    const hashedPassword = await hashPassword(password);
    
    const query = `
      INSERT INTO users (username, email, password)
      VALUES ($1, $2, $3)
      RETURNING *
    `;
    
    const result = await pool.query(query, [username, email, hashedPassword]);
    return result.rows[0];
  } catch (error) {
    console.error('Error creating user:', error);
    throw error;
  }
};

// 验证密码
export const validatePassword = async (password: string, hashedPassword: string): Promise<boolean> => {
  return await comparePassword(password, hashedPassword);
};

// 更新用户筹码
export const updateUserChips = async (id: number, chips: number): Promise<User | null> => {
  try {
    const query = `
      UPDATE users
      SET chips = $1, updated_at = CURRENT_TIMESTAMP
      WHERE id = $2
      RETURNING *
    `;
    
    const result = await pool.query(query, [chips, id]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error updating user chips:', error);
    throw error;
  }
};